import { sendData } from 'socketApi';
import { Sensor } from 'store';

type Props = {
  sensor: Sensor;
};

const LedControl = ({ sensor }: Props) => {
  const is2Disabled = sensor.channel2.sequenceNumber === null;
  const is3Disabled = sensor.channel3.sequenceNumber === null;

  const on = (channelNumber: number, onOff: boolean) => () => {
    if (channelNumber === 2 && sensor.channel2.sequenceNumber !== null) {
      const mSeq = sensor.channel2.sequenceNumber >> 8;
      const lSeq = sensor.channel2.sequenceNumber - (mSeq << 8);
      const lValue = onOff ? 200 : 0;
      sendData([2, 0x10, mSeq, lSeq, 0, lValue]);
    }

    if (channelNumber === 3 && sensor.channel3.sequenceNumber !== null) {
      const mSeq = sensor.channel3.sequenceNumber >> 8;
      const lSeq = sensor.channel3.sequenceNumber - (mSeq << 8);
      const lValue = onOff ? 200 : 0;
      sendData([3, 0x10, mSeq, lSeq, 0, lValue]);
    }
  }; 

  return (
    <div>
      <button
        onClick={on(2, true)}
        disabled={is2Disabled}
        className="btn btn-xs btn-primary"
      >
        2on
      </button>

      <button
        onClick={on(2, false)}
        disabled={is2Disabled}
        className="btn btn-xs btn-primary"
      >
        2off
      </button>

      <button
        onClick={on(3, true)}
        disabled={is3Disabled}
        className="btn btn-xs btn-secondary"
      >
        3on
      </button>

      <button
        onClick={on(3, false)}
        disabled={is3Disabled}
        className="btn btn-xs btn-secondary"
      >
        3off
      </button>
    </div>
  );
};

export default LedControl;

